package com.bnz.servlet;

import cn.hutool.core.util.StrUtil;
import com.bnz.pojo.Cart;
import com.bnz.pojo.Dessert;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

@WebServlet("/cart")
public class CartServlet extends HttpServlet {


    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.1 得到请求参数
        String cmd = req.getParameter("cmd");
        //1.2 根据请求参数调用方法
        if (StrUtil.isNotBlank(cmd)){
            if ("add".equals(cmd)){         //1. 添加购物车
                add(req,resp);
            }
            if ("remove".equals(cmd)){      //2. 移除购物车
                remove(req,resp);
            }
        }
    }


    //1. 添加购物车
    private void add(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //1.1 得到要添加的商品id
        String did = req.getParameter("did");
        //1.2 得到ServletContext中的所有商品信息
        ServletContext servletContext = this.getServletContext();
        Map<String, Dessert> desserts = (Map<String, Dessert>) servletContext.getAttribute("desserts");
        //1.3 根据key得到值
        Dessert dessert = desserts.get(did);
        //1.4 得到购物车对象
        //1.4.1 得到session对象
        HttpSession session = req.getSession();
        //1.4.2 从session中得到购物车
        Cart cart = (Cart) session.getAttribute("cart");
        //1.4.3 如果第一次购买商品，没有购物车对象就构造一个
        if (cart == null){
            cart = new Cart();
        }
        //1.4.4 添加商品到购物车中
        cart.add(dessert);
        //1.4.5 将购物车放到session中
        session.setAttribute("cart",cart);
        //1.4.6 跳转到购物车列表
        resp.sendRedirect("/cart_list.jsp");

    }

    //2. 移除购物车
    private void remove(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //2.1 获取商品id
        String did = req.getParameter("did");
        //2.2 得到购物车对象
        //2.2.1 得到session对象
        HttpSession session = req.getSession();
        //2.2.2 从session中取出购物车
        Cart cart = (Cart) session.getAttribute("cart");
        //2.2.3 从购物车对象中移除商品
        cart.remove(did);
        //2.3 跳转到购物车列表
        resp.sendRedirect("/cart_list.jsp");
    }
}
